<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>javaScript实现回到顶部效果</title>
    <style type="text/css">
        .content{
            width: 1190px;
            margin: 0 auto;
            text-align: center;
        }
        #btn {
            display: none;
            width: 40px;
            height: 40px;
            position: fixed;
            left: 50%;
            margin-left: 610px;
            bottom: 30px;
            background: #f00 url("images/top-btn.png") no-repeat left top;
        }
        #btn:hover {
            background: url("images/top-btn.png") no-repeat left -40px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function(){
          var btn = document.getElementById("btn");
          var clientHeight=document.documentElement.clientHeight;
          var timer = null;
          var isStop=false;
//            滚动条滚动时触发
          window.onscroll = function(){
//              显示隐藏按钮
              var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
              if(scrollTop >=clientHeight){
                btn.style.display = "block";
              }else{
                btn.style.display = "none";
              }
              if(isStop){
                  clearInterval(timer);
              }
              isStop = true;
          };
//            点击按钮返回顶部
          btn.onclick = function(){
              timer = setInterval(function(){
                  isStop = false;
                  var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
                  var speed = Math.ceil(scrollTop / 20);
                  if(scrollTop == 0){
                      clearInterval(timer);
                  }else{
                      document.documentElement.scrollTop = document.body.scrollTop -= speed;
                  }
              },30);
          };
        };
    </script>
</head>
<body>
    <div class="content">
        <img src="images/top-content.jpg" alt="淘宝截图"/>
    </div>
    <a href="javascript:;" id="btn" title="回到顶部"></a>
</body>
</html>